package com.example.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.eureka.EurekaServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @ClassName DiscoveryClientTestController
 * @Description TODO
 * @Author: XMK
 * @Date: 2021/10/21 11:56
 * @Version: 1.0
 */
@RestController
@RequestMapping("/client")
public class DiscoveryClientTestController {

    @Autowired
    private DiscoveryClient client;

//    @Autowired
//    private EurekaClient eurekaClient;

    @Autowired
    private LoadBalancerClient lb;

    @GetMapping("/getServices")
    public String getServices() {
        List<String> services = client.getServices();
        services.stream().forEach(System.out::println);

        return "getServices";
    }

    @GetMapping("/getInstances")
    public List<ServiceInstance> getInstances(String id) {
        List<ServiceInstance> instances = client.getInstances(id);

        instances.stream().forEach(i -> {
            Map<String, String> metadata = i.getMetadata();
            System.out.println(metadata.get("testp"));

            EurekaServiceInstance instance = (EurekaServiceInstance) i;
//            instance.get

        });

        return instances;
    }

//    @GetMapping("/eureka-get")
//    public List<InstanceInfo> getInstance(String id) {
//        List<InstanceInfo> instancesById = eurekaClient.getInstancesById(id);
//        instancesById.stream().forEach(i -> {
//            System.out.println(i.getAppName());
//            System.out.println(i.getMetadata());
//            System.out.println(i.getStatus());
//
//        });
//
//        return instancesById;
//    }

    @GetMapping("/lb")
    public String lb() {

        ServiceInstance instance = lb.choose("eureka-provider");

        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/demo/hello";
        System.out.println(url);

        RestTemplate restTemplate = new RestTemplate();
        String aa = restTemplate.getForObject(url, String.class);

        return aa;
    }
}
